package com.itheima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.UserConstans;
import com.heima.model.common.dtos.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.itheima.user.feign.AuthorFeign;
import com.itheima.user.feign.WmUserFeign;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private AuthorFeign authorFeign;


    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        if (ObjectUtil.isEmpty(authDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检测分页参数
        authDto.checkParam();

        Page page = new Page(authDto.getPage(),authDto.getSize());

        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.lambdaQuery();
        if (authDto.getStatus() != null){
            lambdaQuery.eq(ApUserRealname::getStatus,authDto.getStatus());
        }

        IPage page1 = page(page, lambdaQuery);

        PageResponseResult responseResult = new PageResponseResult(authDto.getPage(),authDto.getSize(), (int) page1.getTotal());

        responseResult.setCode(200);
        responseResult.setData(page1.getRecords());
        return responseResult;
    }



    @GlobalTransactional
    @Override
    @Transactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        if (dto == null || status == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Boolean check = statusCheck(status);
        if (check){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname userRealname = new ApUserRealname();
        userRealname.setId(dto.getId());
        userRealname.setStatus(status);
        if (dto.getMsg() != null){
            userRealname.setReason(dto.getMsg());
        }
        save(userRealname);

        if (status.equals(UserConstans.PASS_AUTH)){
            ResponseResult wmUserAndAuthor = createWmUserAndAuthor(dto);
            if(wmUserAndAuthor != null){
                return wmUserAndAuthor;
            }
            //TODO 发送通知消息
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 状态码检查 :测试客户端传来的状态码格式是否正确
     */
    public Boolean statusCheck(Short status){
        if (status == null || (!status.equals(UserConstans.FAIL_AUTH) && !status.equals(UserConstans.PASS_AUTH))){
            return true;
        }
        return false;
    }

    /**
     * 向自媒体表和作者表中添加数据
     */
    private ResponseResult createWmUserAndAuthor(AuthDto dto){
        //获取审核信息表中的对应用户的数据
        ApUserRealname byId = getById(dto.getId());

        //根据审核信息表中提供的用户的账号来查询用户信息表中对应用户的数据
        ApUser apUser = apUserMapper.selectById(byId.getUserId());

        //判断用户是否存在
        if (ObjectUtil.isEmpty(apUser)){
            //不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //存在
        ResponseResult<WmUser> result = wmUserFeign.findById(apUser.getId());
        WmUser wmUser = result.getData();
        if (wmUser == null || wmUser.getId()==null) {
            wmUser = new WmUser();
            //设置ApUserId

            //将用户信息表中的主键id添加到媒体表的用户id中
            wmUser.setApUserId(apUser.getId());
            //添加数据到媒体表创建时间字段
            wmUser.setCreatedTime(new Date());
            // 添加盐字段数据
            wmUser.setSalt(apUser.getSalt());
            //添加用户名到登录用户名
            wmUser.setName(apUser.getName());
            //添加密码到登录密码
            wmUser.setPassword(apUser.getPassword());
            // 修改状态码为9(审核通过)
            wmUser.setStatus(9);
            //添加手机号
            wmUser.setPhone(apUser.getPhone());

            wmUserFeign.insert(wmUser);
        }

        // 创建作者账号
        createAuthor(wmUser);
        // 修改媒体人身份
        apUser.setFlag(UserConstans.WM_TYPE_SIGN);

        // 修改用户信息表
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 向作者表中添加数据
     * @param wmUser
     * @return
     */
    private void createAuthor(WmUser wmUser){
        Integer apUserId = wmUser.getApUserId();
        ResponseResult<ApAuthor> feignById = authorFeign.findById(apUserId);
        ApAuthor apAuthor = feignById.getData();
        if(apAuthor == null || apAuthor.getId() == null){
            apAuthor = new ApAuthor();
            //作者名称
            apAuthor.setName(wmUser.getName());
            //作者身份
        /*
        0 爬取数据		1 签约合作商			2 平台自媒体人
        */
            apAuthor.setType(UserConstans.AUTH_TYPE_SIGN);
            //账号创建时间
            apAuthor.setCreatedTime(new Date());
            //社交账号
            apAuthor.setUserId(apUserId);

            authorFeign.insert(apAuthor);
        }
    }
}
